package com.fingard.dsp.bank.directbank.scb02;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.io.FileHelper;

/**
 * @author XueJy on 2018/8/6.
 * @version 1.0
 */

public class SCB02Transaction extends SCB02Base implements ITransaction {

    DecimalFormat df = new DecimalFormat("0.00");


    public static int differentDaysByMillisecond(Date date1,Date date2)
    {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }


    /**
     * 7516
     * 历史明细查询
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //BankCode TransType TransSeqID
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        String actNum = p_req7516.actNum;
        try {
            //账号地区区域码
            String actArea = p_req7516.actArea;
            //币种
            String actCur = p_req7516.actCur;
            //查询起止时间
            Calendar calendarFrom = Calendar.getInstance();
            calendarFrom.setTime(p_req7516.getDateFrom());
            Calendar calendarTo = Calendar.getInstance();
            calendarTo.setTime(p_req7516.getDateTo());
            //超出当前时间则使用当前 时间
            if (calendarTo.getTime().getTime() > System.currentTimeMillis()) {
                calendarTo.setTime(new Date());
            }

            //List<String[]> prebalances = new ArrayList<>();
            //存放历时余额详情Map Key为日期yyyy-MM-dd ,Value为当日余额
            int numOfDate =differentDaysByMillisecond(p_req7516.getDateFrom(),p_req7516.getDateTo())+ 1;

            Map<String, String> hisTransactionMap = new HashMap<String, String>(numOfDate);
            for (int x = 0; x < numOfDate; x++) {
                //key :yyyyMMdd  value String[]
                hisTransactionMap.put(Format.Date8Format.format(calendarFrom.getTime()), "");
                calendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            }
            //渣打银行client接收来自渣打银行SCB回盘今日/每日明细文件所存放的路径
            //D:\Workspaces\FilesForDevelop\BankPort\SCB02\host2host\documents\reportscust\in\rpt\
            String detailsFilePath = getH2HPath("ReceiveSCBPriorDayDetailsFilePath");
            //备份路径
            //D:\Workspaces\SCB02\reportscust\in\rpt\
            String localTxnFile = getH2HPath("localTxnFilePath");
            //<group id>.REPORTSCUST.<yyyymmddhhmmssXX>.<filesize>.txn
            //e.g. GCNA5011.REPORTSCUST.20140912130222VE.10229.txn
            // 是否是加强型MT历史文件 是则文件拷贝文件路径和读取需改变
            String clientNum = getBankConfig().getValueAsString("clientNum");
            if ("1".equals(clientNum)) {
                folderToFolder(detailsFilePath, localTxnFile, "1");
            }else {
                //拷贝文件到本地路径
                folderToFolder(detailsFilePath, localTxnFile);
            }
            // 读取配置，判断是否是通威的，是则走新代码
            String whichclient = getBankConfig().getValueAsString("whichclient");

            if(whichclient != "" && "tw".equals(whichclient)) {
                //region 读取交易明细信息
                int readHisNum = 0; // 读取的历史明细文件数
                boolean reandActNum = false; // 是否有该账号记录，没有则返回提示信息
                boolean emptyTran = false; // 有该账号，是否有明细记录
                for (Map.Entry<String, String> history : hisTransactionMap.entrySet()) {
                    String fileDatePath = getTrimPath(localTxnFile) + File.separator + history.getKey().substring(0, 6) + File.separator + history.getKey().substring(6, 8);
                    List<String> fileNames = getDirectoryAllFileName(fileDatePath);
                    // 找到早上发的记录PRIORCUST.rpt
                    for (String fileName : fileNames) {
                        // 该文件一天只有一个
                        if (fileName.contains("PRIORCUST.rpt")) {
                            try {
                                String alltext = "";
                                synchronized (this) {
                                   //读取历史明细内容
                                    alltext = FileHelper.readFileText(fileDatePath + File.separator + fileName, getCharset());
                                }
                                readHisNum ++;
                                // 首先查看文件中是否有该账号的记录
                                if (alltext.contains(actNum)) {
                                    // 有交易P就提供交易记录，没有（只有H）
                                    if (!alltext.contains("P,")) {
                                        // 没有明细记录
                                    } else {
                                        // 存在交易记录
                                        emptyTran = true;
                                        retAts.writeRespCode("0");
                                        reandActNum = true;
                                        String[] hisArr = alltext.split(actNum);// 截取出该账号的记录
                                        for (int i = 1; i < hisArr.length; i ++) {
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            String[] oneArr = hisArr[i].split(",");
                                            tmpRetDetail.accBal = oneArr[6];
                                            tmpRetDetail.cur = oneArr[1];
                                            tmpRetDetail.actArea = actArea;
                                            tmpRetDetail.actNum = actNum;
                                            // 交易日期
                                            String tranDate = oneArr[3].substring(6) + "-" + oneArr[3].substring(3, 5) + "-" + oneArr[3].substring(0, 2);
                                            Date date = new DateFormat2("yyyy-MM-dd").parse(tranDate);
                                            tmpRetDetail.tranDate = Format.Date10Format.format(date);
                                            tmpRetDetail.tranTime = Format.DateTimeFormat.format(date);
                                            tmpRetDetail.valueDate = oneArr[10].substring(6) + "-" + oneArr[10].substring(3, 5) + "-" + oneArr[10].substring(0, 2);;// 起息日
                                            String cdFlag = "";
                                            if ("D".equals(oneArr[11])) {
                                                cdFlag = "1";
                                            } else {
                                                cdFlag = "2";
                                            }
                                            tmpRetDetail.cdFlag = cdFlag;
                                            if(oneArr[12].contains("-")){
                                                // 交易金额
                                                tmpRetDetail.tranAmt = oneArr[12].substring(1);
                                            } else {
                                                tmpRetDetail.tranAmt = oneArr[12];
                                            }
                                            retAts.writeRetDetail(tmpRetDetail);
                                        }

                                    }
                                }
                                // 解析文件 首先查看是否有该账号的记录
                            }catch (Exception ex) {
                                WriteBankLogLn("解析：" + fileName + " 文件异常：" + ex);
                            }
                    //        break; // 该文件只有一个，查到了就退出循环
                        }
                    }
                }
                if (emptyTran == false){
                    if (!retAts.hasWrittenRespCode) {
                        retAts.writeRespCode("0");
                    }
                    retAts.writeRespInfo("交易为空");
                    retAts.writeEnd();
                    return retAts;
                }
                if (readHisNum == 0) {
                    if (!retAts.hasWrittenRespCode) {
                        retAts.writeRespCode("-1");
                    }
                    retAts.writeRespInfo("没有历史明细文件");
                    retAts.writeEnd();
                    return retAts;
                }
                if (reandActNum == false) {
                    retAts.writeRespInfo("没有该账号信息");
                    if (!retAts.hasWrittenRespCode) {
                        retAts.writeRespCode("-1");
                    }
                    retAts.writeEnd();
                    return retAts;
                }

            } else if(clientNum != "" && "1".equals(clientNum)){
                int fileNum = 0;
                for (Map.Entry<String, String> history : hisTransactionMap.entrySet()) {//指定日期路径
                 String fileDatePath = getTrimPath(localTxnFile) + File.separator + history.getKey().substring(0, 6) + File.separator + history.getKey().substring(6, 8);

                List<String> fileNames = getDirectoryAllFileName(fileDatePath);
                    for (String fileName : fileNames) {
                        if (fileName.contains("MT940")) {
                            try {
                                fileNum++;
                                String alltext = "";
                                synchronized (this) {
                                    // 读取文件内容
                                    alltext = FileHelper.readFileText(fileDatePath + File.separator + fileName, getCharset());
                                }
                                alltext = alltext.replace("\n", "");
                                //对单个文件进行解析查找对应的账号明细信息 //:25: 跟账号
                                String[] sArray1 = alltext.split(":25:");
                                if (sArray1.length > 1) {
                                    for (String reqTxt : sArray1) {
                                        if (reqTxt.startsWith(actNum)) {
                                            //获取openingBalance
                                            String[] openingBal1 = reqTxt.split(":60F:");
                                            String cur = "";
                                            if (openingBal1.length > 1) {
                                                String openingBal2 = (openingBal1[1].split("\r\n"))[0];// :60F:C200316CNY0,00获得":60:"后的数据
                                                 cur = openingBal2.substring(7, 10);
                                            }
                                            // 获得的所有明细
                                            String[] txns = openingBal1[1].split(":61:");
                                            if (txns.length > 1) {
                                                for (int i = 1; i < txns.length; i++) {
                                                    // oneTran的长度有好几种可能，正常7行，一行61的,六行86的；61的是不管oneTran多长都要读取的
                                                    String[] oneTran = txns[i].split("\r");
                                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                                    // [0]后是:61:后的数据
                                                    String valueDateStr = oneTran[0].substring(0, 6);// 获得起息日200316
                                                    Date valueDate = Format.Date6Format.parse(valueDateStr);
                                                    tmpRetDetail.valueDate = Format.Date10Format.format(valueDate);// 起息日
                                                    tmpRetDetail.tranDate = Format.Date10Format.format(valueDate);// 交易日期
                                                    tmpRetDetail.tranTime = Format.DateTimeFormat.format(valueDate);// 交易时间
                                                    tmpRetDetail.cur = this.getBankConfig().getMapKeyByValue("currencyMapping",cur);
                                                    String cdFlag = "";// 借贷标志
                                                    cdFlag = oneTran[0].substring(10, 11);
                                                    if ("C".equals(cdFlag)) {
                                                        tmpRetDetail.cdFlag = "2";//贷标志
                                                        tmpRetDetail.recAccName = actNum;
                                                    } else if ("D".equals(cdFlag)) {
                                                        tmpRetDetail.cdFlag = "1";//借标志
                                                        tmpRetDetail.actNum = actNum;
                                                    }
                                                    String tranAmt = "";// 交易金额
                                                    tranAmt = oneTran[0].substring(12, txns[i].indexOf(",") + 3);
                                                    tranAmt = convertCommaToPoint(tranAmt);
                                                    BigDecimal amount = new BigDecimal(tranAmt);
                                                    //交易金额
                                                    tmpRetDetail.tranAmt = df.format(amount);

                                                    // 对于86后参数行数的多种可能，为6行时
                                                    if (oneTran.length == 7) {
                                                        // 对于86后的信息处理，参数个数有1~6个
                                                        String info1 = oneTran[1].substring(4);// 支付信息说明1
                                                        //tmpRetDetail.actNum = oneTran[2];// 付方户名 代码中没有付方户名字段
                                                        if(oneTran[0].substring(1,16).contains("DY")){
                                                            tmpRetDetail.recAccName = oneTran[3];// 收方户名
                                                            tmpRetDetail.recAccNum = oneTran[4];// 收方账号
                                                        } else if(oneTran[0].substring(1,16).contains("CY")){
                                                            tmpRetDetail.recAccName = oneTran[2];// 收方户名
                                                            tmpRetDetail.recAccNum = oneTran[6];// 收方账号
                                                        }
                                                        String info2 = oneTran[5];// 支付信息说明2
                                                        tmpRetDetail.actNum = oneTran[6];// 付方账号
                                                        if ("".equals(info1) || "".equals(info2)) {
                                                            tmpRetDetail.usage = info1 + info2;
                                                        } else {
                                                            tmpRetDetail.usage = info1 + "-" + info2;
                                                        }
                                                        tmpRetDetail.comment = tmpRetDetail.usage;
                                                    } else {
                                                        // 86:后数据行数非六行，把86后的数据全放到附言、备注中
                                                        if(txns[i].contains("Sweep")&&txns[i].contains("to")){
                                                            //收方账号取to和SWEEP之间的账号
                                                            tmpRetDetail.recAccName = txns[i].substring(txns[i].indexOf("to") + 2, txns[i].indexOf("SWEEP")).trim();//对方账户名称
                                                        } else if(txns[i].contains("Sweep")&&txns[i].contains("from")){
                                                            //收方账号取from和SWEEP之间的账号
                                                            tmpRetDetail.recAccName = txns[i].substring(txns[i].indexOf("from") + 4, txns[i].indexOf("SWEEP")).trim();//对方账户名称
                                                        }
                                                        tmpRetDetail.usage = txns[i].split(":86:")[1];
                                                        tmpRetDetail.comment = tmpRetDetail.usage;
                                                    }
                                                    retAts.writeRetDetail(tmpRetDetail);
                                                }

                                            }
                                        }
                                    }
                                } else {
                                    retAts.writeRespInfo("没有历史明细");
                                    retAts.writeRespCode("0");
                                }
                            } catch (Exception e) {
                                WriteBankLogLn("解析：" + fileName + " 文件异常：" + e);
                                retAts.writeRespInfo("解析：" + fileName + " 文件异常：" + e);
                                retAts.writeRespCode("-1");
                            }

                        }
                    }
                }

                if (fileNum == 0){
                    retAts.writeRespInfo("没有历史明细");
                    retAts.writeRespCode("0");
                }
            }else {
                // 文件格式为MT490，非加强型
                //region 读取交易明细信息
                int fileNum = 0;
                for (Map.Entry<String, String> history : hisTransactionMap.entrySet()) {
                    //指定日期路径
                    String fileDatePath = getTrimPath(localTxnFile) + File.separator + history.getKey().substring(0, 6) + File.separator + history.getKey().substring(6, 8);
                    List<String> fileNames = getDirectoryAllFileName(fileDatePath);
                    for (String fileName : fileNames) {
                        if (fileName.contains("MT940")) {
                            try {
                                fileNum++;
                                String alltext = "";
                                synchronized (this) {
                                    //读取文件内容
                                    alltext = FileHelper.readFileText(fileDatePath + File.separator + fileName, getCharset());
                                }
                                //对单个文件进行解析查找对应的账号明细信息 //:25: 跟账号
                                String[] sArray1 = alltext.split(":25:");
                                if (sArray1.length>1 && sArray1[1].startsWith(actNum)) {
                                    //获取openingBalance
                                    String[] openingBal1 = sArray1[1].split(":60F:");
                                    if (openingBal1.length > 1) {
                                        String openingBal2 = (openingBal1[1].split("\r\n"))[0];
                                        //金额
                                        String startBalance = openingBal2.substring(10, openingBal2.length());
                                        String cur = openingBal2.substring(7, 10);
                                        startBalance = convertCommaToPoint(startBalance);
                                        //若为D前面增加－
                                        if ("D".equals(openingBal2.substring(0, 1))) {
                                            startBalance = "-" + startBalance;
                                        }
                                        String[] tranTxts = sArray1[1].split(":62F:");// 便于后面截取每条记录倒数第二行的收款人
                                        String[] txns = tranTxts[0].split(":61:");
                                        //String[] txns = sArray1[1].split(":61:");
                                        if (txns.length > 1) {

                                            for (int i = 1; i < txns.length; i++) {
                                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                                String valueDateStr = txns[i].substring(0, 6);
                                                Date valueDate = Format.Date6Format.parse(valueDateStr);
                                                String transDateStr = txns[i].substring(6, 10);
                                                tmpRetDetail.cur = convertCurToATS(cur);
                                                tmpRetDetail.actArea = actArea;
                                                tmpRetDetail.actNum = actNum;
                                                //region 确定借贷标志 Debit / Credit Flag （1:支出、2:收入）
                                                String cdFlag = "";
                                                if ("D".equals(txns[i].substring(10, 11))) {
                                                    cdFlag = "1";
                                                } else {
                                                    cdFlag = "2";
                                                }
                                                tmpRetDetail.cdFlag = cdFlag;
                                                //BC3/ 付款时候的收方名称    /OC3/收款时候的付款名称
                                                String oppName = "";
                                                String oppNameLineFlag = "/BC3/";
                                                if ("2".equals(cdFlag)) {
                                                    oppNameLineFlag = "/OC3/";
                                                }
                                                String[] oppNameLine = txns[i].split(oppNameLineFlag);
                                                if (oppNameLine.length > 1) {
                                                    oppName = oppNameLine[1].split("\r\n")[0].split("/")[0];
                                                }
                                                tmpRetDetail.recAccName = oppName;
                                                tmpRetDetail.recAccBank = "";
                                                tmpRetDetail.recAccNum = "";
                                                tmpRetDetail.valueDate = Format.Date10Format.format(valueDate);
                                                valueDate.setMonth(Integer.parseInt(transDateStr.substring(0, 2)) - 1);
                                                valueDate.setDate(Integer.parseInt(transDateStr.substring(2, 4)));
                                                tmpRetDetail.tranDate = Format.Date10Format.format(valueDate);
                                                tmpRetDetail.tranTime = Format.DateTimeFormat.format(valueDate);
                                                //计算当前余额
                                                //获取金额
                                                String trAmount = txns[i].substring(12, txns[i].indexOf(",") + 3);
                                                trAmount = convertCommaToPoint(trAmount);
//                                      Double openingbalance = Double.parseDouble(startBalance);
//                                      Double amount = Double.parseDouble(trAmount);
                                                BigDecimal openingbalance = new BigDecimal(startBalance);
                                                BigDecimal amount = new BigDecimal(trAmount);
                                                //openingbalance已经包含正负.
                                                if ("1".equals(cdFlag)) {
                                                    //保留两位小数位
                                                    startBalance = df.format(openingbalance.subtract(amount));
                                                    //保留两位小数位
                                                } else {
                                                    startBalance = df.format(openingbalance.add(amount));
                                                }
                                                //交易金额
                                                tmpRetDetail.tranAmt = df.format(amount);
                                                //账户余额
                                                tmpRetDetail.accBal = startBalance;

                                                String[] oneTxt = txns[i].split("\n");
                                                tmpRetDetail.comment = oneTxt[oneTxt.length - 1];
                                                tmpRetDetail.usage = oneTxt[oneTxt.length - 1];
                                                //用途 BAI CODE
                                                tmpRetDetail.payCode = txns[i].substring(txns[i].indexOf(",") + 4, txns[i].indexOf(",") + 7).trim();
                                                //detail.Abstr;对账码 customer Reference
                                                //tmpRetDetail.askNumber = txns[i].substring(txns[i].indexOf(",") + 7, txns[i].indexOf("//")).trim();
                                                tmpRetDetail.askNumber = alltext.substring(alltext.indexOf(":20:") + 4,alltext.indexOf(":20:") + 20);
                                                // /PT1/ Payment Details local language 1
                                                String payDetails = "";
                                                String[] payDetailsLine = txns[i].split("/PT1/");
                                                if (payDetailsLine.length > 1) {
                                                    payDetails = payDetailsLine[1];
                                                    if (payDetails.split("\r\n").length >0) {
                                                        payDetails = payDetails.split("\r\n")[0].split("/")[0];
                                                    }
                                                }
                                                String[] details = payDetails.split("\\+", -1);
                                                if (details.length == 3) {
                                                    tmpRetDetail.recAccBank = details[0];
                                                    tmpRetDetail.abstr = details[1];
                                                    //tmpRetDetail.usage = details[2];
                                                } else if (details.length > 3) {
                                                    tmpRetDetail.recAccBank = details[0];
                                                    tmpRetDetail.abstr = details[1];
                                                    StringBuilder sb = new StringBuilder();
                                                    for (int x = 2; x < details.length; x++) {
                                                        sb.append("|").append(details[x]);
                                                    }
                                                    sb.delete(0, 1);
                                                    //tmpRetDetail.usage = sb.toString();
                                                } else {
                                                    //tmpRetDetail.usage = payDetails;
                                                }
                                                if (txns.length == 3) {
                                                    //tmpRetDetail.usage = txns[2];
                                                }

                                                retAts.writeRetDetail(tmpRetDetail);
                                            }
                                        }
                            }
                                } else {
                                    retAts.writeRespInfo("没有历史明细");
                                    retAts.writeRespCode("0");
                                }
                            } catch (Exception ex) {
                                WriteBankLogLn("解析：" + fileName + " 文件异常：" + ex);
                            }
                        }
                    }
                }
                if (fileNum == 0){
                    retAts.writeRespInfo("没有历史明细");
                    retAts.writeRespCode("0");
                }
            }
        } catch (Exception ex) {
            WriteBankLogLn(ex);
            //执行状态
            if (!retAts.hasWrittenRespCode) {
                retAts.writeRespCode("-1");
            }
            //执行结果描述
            if (!retAts.hasWrittenRespInfo) {
                retAts.writeRespInfo("历史明细查询异常。");
            }
            retAts.writeEnd();
            return retAts;
        }
        if (!retAts.hasWrittenRespCode) {
            retAts.writeRespCode("0");
        }
        if (!retAts.hasWrittenRespInfo) {
            retAts.writeRespInfo("查询成功。");
        }
        retAts.writeEnd();
        return retAts;
    }

    /**
     * 7515
     * 今日流水查询
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {

        //BankCode TransType TransSeqID
        RetAtsTrans retAts = new RetAtsTrans(p_req7515.reqHeader);
        //写返回ATS的统一头部信息
        retAts.writeStart();
        // String transTime = _ClientReqDoc.SelectSingleNode("descendant::TransTime").InnerText;
        String actNum = p_req7515.actNum;
        String reqSeqId = p_req7515.reqHeader.transSeqID;
        try {
            //账号地区区域码
            String actArea = p_req7515.actArea;
            //币种
            String actCur = p_req7515.actCur;
            //渣打银行client接收来自渣打银行SCB回盘今日/每日明细文件所存放的路径
            String detailsFilePath = getH2HPath("ReceiveSCBPriorDayDetailsFilePath");
            String localTxnFile = getH2HPath("localTxnFilePath");
            //<group id>.REPORTSCUST.<yyyymmddhhmmssXX>.<filefsize>.txn
            //e.g. GCNA5011.REPORTSCUST.20140912130222VE.10229.txn
            //拷贝文件到本地路径
            folderToFolder(detailsFilePath, localTxnFile);
            String dateStr = Format.Date8Format.format(new Date());
            //String dateStr = "20200213";
            String datePath = getTrimPath(localTxnFile) + File.separator + dateStr.substring(0, 6) + File.separator + dateStr.substring(6, 8);
            //被筛选文件
            List<String> allDetailsFileNames = getDirectoryAllFileName(datePath);
            //筛选结果文件
            List<String> detailsFileNames = new ArrayList<String>();
            List<RetAtsTransDetail> retDetails = new ArrayList<RetAtsTransDetail>();
            //GCNA5011.REPORTSCUST.20170402044147P6.QLPAY008R.5278.MT942-UTF8.rpt  GCNA5011.REPORTSCUST.20170402044147P6.QLPAY008R.5278.MT942-UTF8.rpt
//            Calendar createDate = Calendar.getInstance();
            // 读取配置，判断是否是通威的，是则走新代码
            String whichclient = getBankConfig().getValueAsString("whichclient");
            if(whichclient != "" && "tw".equals(whichclient)) {
                // 最新的今日明细文件  最晚的创建日期
                String todayFileName = "";
                long timeTmp = 0;
                for(String twFileName : allDetailsFileNames) {
                    if (twFileName.contains("INTRACUST.rpt")) {
                        File file = new File(datePath + "\\" + twFileName);
                        long time = file.lastModified();
                        if (time > timeTmp) {
                            todayFileName = twFileName;
                            timeTmp = time;
                        }
                    }
                }
                try {
                    String allContent = "";
                    synchronized (this) {
                        // 读取文件内容
                        allContent = FileHelper.readFileText(getTrimPath(datePath) + File.separator + todayFileName, getCharset());
                        if (allContent == null) {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo("没有交易内容");
                            retAts.writeEnd();
                            return retAts;
                        }
                    }
                    // 首先查看文件中是否有该账号的记录
                    if (allContent.contains(actNum)) {
                        // 有交易(I)就提供交易信息，没有(只有H)就只有余额信息
                        if (!allContent.contains("I,")) {
                            // 没有交易
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo("交易为空");
                            retAts.writeEnd();
                            return retAts;
                        } else {
                            retAts.writeRespCode("0");
                            // 存在交易记录，先按账号切割
                            String[] twDetails = allContent.split(actNum);
                            // 读取切割出来的的下一部分，以换行符切割
                            String[] twDetailArrI = twDetails[1].split("\n");
                            for (int i = 1; i < twDetailArrI.length; i ++) {
                                // 一条交易记录 判断是否是I
                                if (twDetailArrI[i].contains("I,")){
                                    String[] twDetailArrIOne = twDetailArrI[i].split(",");
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    tmpRetDetail.actArea = actArea;
                                    tmpRetDetail.actNum = actNum;
                                    tmpRetDetail.recAccBank = "";
                                    tmpRetDetail.recAccNum = "";
                                    // 交易日期
                                    String tranDate = twDetails[1].split(",")[3].substring(6) + "-" + twDetails[1].split(",")[3].substring(3, 5) + "-" + twDetails[1].split(",")[3].substring(0, 2);
                                    Date date = new DateFormat2("yyyy-MM-dd").parse(tranDate);
                                    tmpRetDetail.tranDate = Format.Date10Format.format(date);
                                    tmpRetDetail.tranTime = Format.DateTimeFormat.format(date);
                                    String cdFlag = "";
                                    if ("D".equals(twDetailArrIOne[3])){
                                        cdFlag = "1";
                                    } else {
                                        cdFlag = "2";
                                    }
                                    tmpRetDetail.cdFlag = cdFlag;
                                    String valueDate = twDetailArrIOne[2].substring(6) + "-" + twDetailArrIOne[2].substring(3, 5) + "-" + twDetailArrIOne[2].substring(0, 2);
                                    tmpRetDetail.valueDate = valueDate;// 起息日

                                    if(twDetailArrIOne[4].contains("-")){
                                        // 交易金额
                                        tmpRetDetail.tranAmt = twDetailArrIOne[4].substring(1);
                                    } else {
                                        tmpRetDetail.tranAmt = twDetailArrIOne[4];
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                }else if (twDetailArrI[i].startsWith("H,")){
                                    //该账号记录读取完毕
                                    break;
                                }
                            }
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("没有该账号的记录");
                        retAts.writeEnd();
                        return retAts;
                    }

                } catch (Exception ex){
                    WriteBankLogLn("解析：" + todayFileName + " 文件异常：" + ex);
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("解析：" + todayFileName + " 文件异常：" + ex);
                }
            } else {
                // 不是通威
                int fileNum = 0;
                for (String fileName : allDetailsFileNames) {
                    if (fileName.contains("MT942")) {
                        //查找15分钟内的MT942文件
//                    String[] nameSplit = fileName.split("\\.");
//                    Date fileCreateDate = Format.DateTime14Format.parse(nameSplit[2].substring(0, 14));
//                    createDate.setTime(fileCreateDate);
//                    createDate.add(Calendar.MINUTE, 15);
//                    if (createDate.getTimeInMillis() > System.currentTimeMillis()) {
//                    }
                        fileNum ++;
                        detailsFileNames.add(fileName);
                    }
                }
                if (fileNum == 0) {
                    retAts.writeRespInfo("没有今日明细");
                    retAts.writeRespCode("0");
                }
                for (String fileName : detailsFileNames) {
                    try {
                        String alltext = "";
                        synchronized (this) {
                            //读取文件内容
                            alltext = FileHelper.readFileText(getTrimPath(datePath) + File.separator + fileName, getCharset());
                        }
                        //对单个文件进行解析查找对应的账号明细信息 //"H", 明细头记录拆分符
                        String[] sArray1 = alltext.split(":25:");
                        if (sArray1.length > 1 && sArray1[1].startsWith(actNum)) {
                            String[] tranTxts = sArray1[1].split("-}");// 便于后面截取每条记录倒数第二行的收款人
                            String[] txns = tranTxts[0].split(":61:");
                            if (txns.length > 1) {
                                for (int i = 1; i < txns.length; i++) {
                                    RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                    String valueDateStr = txns[i].substring(0, 6);
                                    Date valueDate = Format.Date6Format.parse(valueDateStr);
                                    String transDateStr = txns[i].substring(6, 10);
                                    tmpRetDetail.actArea = actArea;
                                    tmpRetDetail.actNum = actNum;
//                                    String[] recNameLine = txns[i].split("/BC3/");
//                                    if (recNameLine.length > 1) {
//                                        recName = recNameLine[1].split("\r\n")[0].split("/")[0];
//                                    }
                                    String[] oneTxt = txns[i].split("\n");
                                    tmpRetDetail.recAccName = oneTxt[oneTxt.length - 2];;
                                    tmpRetDetail.recAccBank = "";
                                    tmpRetDetail.recAccNum = "";
                                    tmpRetDetail.comment = oneTxt[oneTxt.length - 1];
                                    tmpRetDetail.usage = oneTxt[oneTxt.length - 1];
                                    tmpRetDetail.valueDate = Format.Date10Format.format(valueDate);
                                    valueDate.setMonth(Integer.parseInt(transDateStr.substring(0, 2)) - 1);
                                    valueDate.setDate(Integer.parseInt(transDateStr.substring(2, 4)));
                                    tmpRetDetail.tranDate = Format.Date10Format.format(valueDate);
                                    tmpRetDetail.tranTime = Format.DateTimeFormat.format(valueDate);
                                    //region 确定借贷标志 Debit / Credit Flag （1:支出、2:收入）
                                    String cdFlag = "";
                                    if ("D".equals(txns[i].substring(10, 11))) {
                                        cdFlag = "1";
                                    } else {
                                        cdFlag = "2";
                                    }
                                    tmpRetDetail.cdFlag = cdFlag;

                                    //计算当前余额
                                    //获取金额
                                    String trAmount = txns[i].substring(12, txns[i].indexOf(",") + 3);
                                    trAmount = convertCommaToPoint(trAmount);
                                    BigDecimal amount = new BigDecimal(trAmount);
                                    //交易金额
                                    tmpRetDetail.tranAmt = df.format(amount);
                                    tmpRetDetail.payCode = txns[i].substring(txns[i].indexOf(",") + 4, txns[i].indexOf(",") + 7).trim();
                                    //detail.Abstr;对账码 customer Reference
                                    //tmpRetDetail.askNumber = txns[i].substring(txns[i].indexOf(",") + 7, txns[i].indexOf("//")).trim();
                                    tmpRetDetail.askNumber = alltext.substring(alltext.indexOf(":20:") + 4,alltext.indexOf(":20:") + 20);
                                    String payDetails = "";
                                    String[] payDetailsLine = txns[i].split("/PT1/");
                                    if (payDetailsLine.length > 1) {
                                        payDetails = payDetailsLine[1];
                                        if (payDetails.split("\r\n").length >0) {
                                            payDetails = payDetails.split("\r\n")[0].split("/")[0];
                                        }
                                    }
                                    String[] details = payDetails.split("\\+", -1);
                                    if (details.length == 3) {
                                        tmpRetDetail.recAccBank = details[0];
                                        tmpRetDetail.abstr = details[1];
//                                        tmpRetDetail.usage = details[2];
                                    } else if (details.length > 3) {
                                        tmpRetDetail.recAccBank = details[0];
                                        tmpRetDetail.abstr = details[1];
                                        StringBuilder sb = new StringBuilder();
                                        for (int x = 2; x < details.length; x++) {
                                            sb.append("|").append(details[x]);
                                        }
                                        sb.delete(0, 1);
                                        //tmpRetDetail.usage = sb.toString();
                                    } else {
                                       // tmpRetDetail.usage = payDetails;
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                    //retDetails.add(tmpRetDetail);
                                }
                            }
                        }
                    } catch (Exception ex) {
                        WriteBankLogLn("解析：" + fileName + " 文件异常：" + ex);
                    }

                }
                //找不到数据则产生查询文件
                /*for (RetAtsTransDetail retDetail : retDetails) {
                    retAts.writeRetDetail(retDetail);
                }*/
            }

        } catch (Exception ex) {
            if (!retAts.hasWrittenRespCode) {
                retAts.writeRespCode("-1");
            }
            WriteBankLogLn("产生异常" + ex);
            if (!retAts.hasWrittenRespInfo) {
                retAts.writeRespInfo("产生异常" + ex);
            }
            //执行结果描述
            retAts.writeEnd();
            return retAts;
        }
        //执行状态
        if (!retAts.hasWrittenRespCode) {
            retAts.writeRespCode("0");
        }
        //执行结果描述
        if (!retAts.hasWrittenRespInfo) {
            retAts.writeRespInfo("成功");
        }
        retAts.writeEnd();
        return retAts;
    }

}
